package com.smh.controller;


import com.smh.model.User;
import com.smh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index")
    public ModelAndView index(){
        ModelAndView view = new ModelAndView();
        view.setViewName("user/index");
        List<User> users = userService.search();
        view.addObject("users",users);
        return view;
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public ModelAndView addView(){
        ModelAndView view = new ModelAndView();
        view.setViewName("user/add");
        return view;
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(User user){
        boolean rs = this.userService.add(user);
        return  "redirect:/user/index";
    }

    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public String delete(String idcardNo){
        boolean rs = this.userService.delete(idcardNo);
        return "redirect:/user/index";//为了使页面数据刷新
    }


    @GetMapping("/update")
    public String update(User user){
        boolean rs = userService.update(user);
        return "redirect:/user/index";
    }


    @RequestMapping("/ajax")
    public String ajaxIndex(){
        return "user/ajax";
    }

    @ResponseBody
    @PostMapping("/save")
    public String save(String name,Integer age,String idcardNo){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        user.setIdcardNo(idcardNo);
        this.add(user);
        return "ok";
    }
    @ResponseBody
    @PostMapping("/getData")
    public List<User> getData(){
        return userService.search();
    }
}
